package com.ark.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ark.yygh.hosp.repository.ScheduleRepostitory;
import com.ark.yygh.hosp.service.DepartmentService;
import com.ark.yygh.hosp.service.HospitalService;
import com.ark.yygh.hosp.service.ScheduleService;
import com.ark.yygh.model.hosp.Schedule;
import com.ark.yygh.vo.hosp.BookingScheduleRuleVo;
import com.ark.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepostitory scheduleRepostitory;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    //上传排班
    @Override
    public void save(Map<String, Object> switchMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(switchMap), Schedule.class);

        //根据医院编号和排版编号
        Schedule targetSchedule = scheduleRepostitory
                .getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        //判断是否存在于数据库
        if (targetSchedule==null){
            //不存在则新增
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepostitory.save(schedule);
        } else {
            //存在则更新
            targetSchedule.setUpdateTime(new Date());
            targetSchedule.setIsDeleted(0);
            targetSchedule.setStatus(1);
            scheduleRepostitory.save(targetSchedule);
        }
    }

    //查询排班列表
    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //对象转换
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        //分页
        Pageable pageable = PageRequest.of(page-1,limit);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Example<Schedule> example = Example.of(schedule, matcher);

        //调用方法
        Page<Schedule> schedulePage = scheduleRepostitory.findAll(example, pageable);
        return schedulePage;
    }

    //删除排班
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        //根据医院编号和排班编号进行查询
        Schedule schedule = scheduleRepostitory.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        //判断
        if (schedule!=null){
            scheduleRepostitory.delete(schedule);
        }
    }

    /**
     * 查询排班规则数据
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //根据工作日期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                    .first("workDate").as("workDate")  //分组字段
                        //统计号源
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")  //可预约数
                .sum("availableNumber").as("availableNumber"),  //剩余预约数
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法
        AggregationResults<BookingScheduleRuleVo> ruleVos
                = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleList = ruleVos.getMappedResults();

        //把日期对应的星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate(); //可预约日期
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate)); //日期对应的星期
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek); //设置星期几的值
        }

        //总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        int total = mongoTemplate
                .aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class)
                .getMappedResults().size();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("bookingScheduleRuleList",bookingScheduleRuleList);
        resultMap.put("total",total);

        //调用方法获取hosname
        String hosname = hospitalService.getHospitalByHoscode(hoscode).getHosname();
        Map<String,String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosname);
        resultMap.put("baseMap",baseMap);

        return resultMap;
    }

    /**
     * 根据医院编号 、科室编号和工作日期，查询排班详细信息
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //查询
        List<Schedule> scheduleList =
                scheduleRepostitory.getScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        //遍历集合封装排班详情数据
        scheduleList.stream().forEach(item ->{
            packageSchedule(item);
        });
        return scheduleList;
    }

    //获取日期对应的星期
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    //封装排班详情数据
    private Schedule packageSchedule(Schedule schedule){
        //医院名称
        schedule.getParam().put("hosname",hospitalService.getHosName(schedule.getHoscode()));
        //科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //日期对应星期
        schedule.getParam().put("dayOfweek",getDayOfWeek(new DateTime(schedule.getWorkDate())));

        return schedule;
    }
}
